<?php
namespace app\common\logic;

class GoodsCategory{
    /**
     * 获取商品一二三级分类
     * @return type
     */
    function get_goods_category_tree(){
        $tree = $arr = $result = array();
        $cat_list = M('goods_category')->where(['is_show' => 1])->order('sort_order')->select();//所有分类
        if($cat_list){
            foreach ($cat_list as $val){
                if($val['level'] == 2){
                    $arr[$val['parent_id']][] = $val;
                }
                if($val['level'] == 3){
                    $crr[$val['parent_id']][] = $val;
                }
                if($val['level'] == 1){
                    $tree[] = $val;
                }
            }

            foreach ($arr as $k=>$v){
                foreach ($v as $kk=>$vv){
                    $arr[$k][$kk]['sub_menu'] = empty($crr[$vv['id']]) ? array() : $crr[$vv['id']];
                }
            }

            foreach ($tree as $val){
                $val['tmenu'] = empty($arr[$val['id']]) ? array() : $arr[$val['id']];
                $result[$val['id']] = $val;
            }
        }
        return $result;
    }

    /**
     * 获取某个商品分类的 儿子 孙子  重子重孙 的 id
     * @param type $cat_id
     */
    function getCatGrandson($cat_id)
    {
        $GLOBALS['catGrandson'] = array();
        $GLOBALS['category_id_arr'] = array();
        // 先把自己的id 保存起来
        $GLOBALS['catGrandson'][] = $cat_id;
        // 把整张表找出来
        $GLOBALS['category_id_arr'] = M('GoodsCategory')->cache(true,TPSHOP_CACHE_TIME)->getField('id,parent_id');
        // 先把所有儿子找出来
        $son_id_arr = M('GoodsCategory')->where("parent_id", $cat_id)->cache(true,TPSHOP_CACHE_TIME)->getField('id',true);
        foreach($son_id_arr as $k => $v)
        {
            $this->getCatGrandson2($v);
        }
        return $GLOBALS['catGrandson'];
    }

    /**
     * 递归调用找到 重子重孙
     * @param type $cat_id
     */
    function getCatGrandson2($cat_id)
    {
        $GLOBALS['catGrandson'][] = $cat_id;
        foreach($GLOBALS['category_id_arr'] as $k => $v)
        {
            // 找到孙子
            if($v == $cat_id)
            {
                $this->getCatGrandson2($k); // 继续找孙子
            }
        }
    }

}
